import CommonUtil from '../utils/common'
import ArrayUtil from '../utils/array'
import { cloneDeep, omitBy } from 'lodash'
import URLUtil from '../utils/url'
import clone from 'clone'

const MICRO_APP_REGEXP = /{microapp:[a-z, A-Z,-]+}/,
  PATH_REGEXT = /\/:{path:[a-z, A-Z,-]+}/,
  PLACEHOLDER_REGEXP = /{[a-z, A-Z,-]+:[a-z, A-Z,-]+}/g

export default (dataList, router, buildMicroAppRoute) => {
  let { routeMap, dynamic } = router.getRouteConfig('pc'),
    actionMap = {}, routePathMap = {}, routeList = []

  // 缓存按钮权限
  dataList.map(data => {
    if (data.type === '3') {
      actionMap[data.parentId] = actionMap[data.parentId] || []
      actionMap[data.parentId].push(data.code.split(':').pop())
    }
  })

  const menuList = dataList.forEach(data => {
    let url = data.uri?.split('?')[0],
      menu = {
        id: data.id,
        parentId: data.parentId,
        meta: {
          id: data.id,
          parentId: data.parentId,
          title: data.name,
          hidden: data.type == '3' ? true : CommonUtil.toBool(data.hidden),
          icon: data.icon,
          type: data.type
        }
      }
    data.uri && (menu.query = URLUtil.getURLParams(data.uri) || {})
    data.target == '3' && (menu.meta.target = '_blank')
    data.target == '2' && (menu.meta.target = 'iframe')

    let holders = {}, routePath = '', params = ''
    // '/rootpath/{microapp:xxxx}/workplace/:{path:xxxx}/{subpath:xxx}?id=xxx&name=xxx'
    if (!url) {
      return menu
    }
    menu.path = url
    menu.original = url
    const matchs = url.match(PLACEHOLDER_REGEXP)
    matchs && matchs.forEach(placeholder => {
      placeholder = placeholder.split(':')
      holders[placeholder[0]] = placeholder[1]
    })
    // 替换占位符
    Object.keys(holders).map(key => {
      if (key !== 'path') {
        menu.path = menu.path.replace(`{${key}:${holders[key]}}`, holders[key])
      }
    })

    routePath = menu.path
    // 匹配 /: 参数
    const match = menu.path.match(PATH_REGEXT)
    if (match) {
      routePath = `${menu.path.substring(0, match.index + 2)}/:path*`
      menu.path = `${menu.path.substring(0, match.index)}/${holders.path}`
    }

    if (routePathMap[routePath]) {
      return menu
    }

    if (holders.microapp) {
      // 构建微应用路由
      return menu
    }

    // 从本地路由配置中获取路由
    let route = routeMap[routePath] || dynamic[routePath]
    if (!route) {
      console.info(`未找到 '${routePath}' 路由配置信息`)
      return menu
    }

    route = clone(route)
    // 合并菜单 meta 到路由
    route.meta = route.meta || {}
    CommonUtil.merge(route.meta, menu.meta)

    // 添加功能权限
    route.meta.authorize = actionMap[route.meta.id] || []

    // 去除子路由中没有 path 的子节点（功能按钮），或标记为绝对路径的子路由
    route.children = route.children?.filter(child => child.path && !child.meta.absolute) || []

    routeList.push(route)
    routePathMap[routePath] = route

    return menu
  })

  // array 转 tree
  const { nodeList, nodeMap } = ArrayUtil.toTree(menuList, 'id', 'parentId')

  // 构建本地注册的路由及菜单
  const roots = router.getRoots(),
    defaultRoot = roots.find(item => item.path === '/' || item.path === ''),
    localMenuList = buildLocalRouteMenu(defaultRoot.children)

  localMenuList.map((menu, index) => {
    nodeList.splice(index, 0, menu)
  })
  // 将路由添加到对应根路由中
  roots.map(root => {
    root.children = root.children || []

    root.children.map(child => {
      child.meta._parent && child.meta.absolute && child.meta._parent.children.splice(child.meta._parent.children.indexOf(child), 1)
    })
    if (root.path == '/') {
      return
    }
    Object.keys(routePathMap).map(path => {
      const route = routePathMap[path]
      if (route.path.startsWith(`${root.path}/`) && route.path != root.path) {
        root.children.push(route)
        routeList.splice(routeList.indexOf(route), 1)
      }
    })
  })
  // 追加新的权限路由到 root 路由下
  defaultRoot.children = defaultRoot.children.concat(routeList.filter(route => route.meta.absolute || !route._parent))

  // 动态路由中的静态路由
  Object.keys(dynamic).map(path => {
    if (dynamic[path].meta?.static) {
      defaultRoot.children.push(dynamic[path])
    }
  })

  // 设置根路由的默认重定向地址
  nodeList.find(node => {
    return setDefaultRedirect(defaultRoot, node)
  })
  return { roots, menuList: nodeList, menuMap: nodeMap }
}

/**
 * 构建本地注册的路由菜单
 * @param {*} router
 */
function buildLocalRouteMenu (children) {
  const menuList = children.map(child => {
    child.meta.id = child.path
    child.meta.parentId = child.meta._parent?.path || null

    // 构建菜单数据
    return {
      id: child.path,
      parentId: child.meta._parent?.path || null,
      path: child.path,
      meta: {
        id: child.path,
        parentId: child.meta._parent?.path || null,
        ...cloneDeep(child.meta)
      }
    }
  })
  const { nodeList, nodeMap } = ArrayUtil.toTree(menuList, 'id', 'parentId')
  // 只返回没有上级节点的菜单数据
  return nodeList
}

function setDefaultRedirect (root, menu) {
  if (root.redirect) {
    return true
  }
  if (!menu.hidden && menu.path) {
    root.redirect = menu.path
    return true
  } else if (menu.children) {
    menu.children.find(child => {
      return setDefaultRedirect(root, child)
    })
  }
  return false
}

function getDefaultRedirect (route) {

}

function hideChildren (routeList) {
  routeList.map(r => {
    if (r.children) {
      if (r.children.length == 0) {
        r.hideChildrenInMenu = true
      } else {
        // 下级节点不为功能菜单并且下级节点没有要显示的菜单
        const c = r.children.find(c => {
          return c.meta?.type != '3' && !c.hidden
        })
        !c && (r.hideChildrenInMenu = true)
      }
    }
    hideChildren(r.children || [])
  })
}
